<?php
/**
 * CenterAction
 * 个人中心-相关设置
 * Author: huqian
 * CreateDate: 2013-08-18
 */

class CenterAction extends CommonAction {
    /**
     * 个人中心-详细资料
     */
    public function index() {
        $province = session('user_province'); //用户所在的省份
        $city = session('user_city'); //用户所在的城市
        //查出所有省份
        $P = M('province');
        $province_list = $P->order('province_code')->select();
        //如果存在省份，查询此省份下的所有市
        if ($province) {
            $province_code = $P->where("province_name = '$province'")->getField('province_code');
            $C = M('city');
            $city_list = $C->where("pro_code = $province_code")->select();
        } else {
            array_unshift($province_list, array('province_code' => 0, 'province_name' => '请选择'));
        }
        $this->assign('title', '个人中心 - ' . C('TITLE'));
        $this->assign('province', $province);
        $this->assign('city', $city);
        $this->assign('province_list', $province_list);
        $this->assign('city_list', $city_list);
        $this->display();
    }

    /**
     * 根据省份id号获取此省份下的所有城市
     *
     */
    function getCity() {
        $city = session('user_city');
        $province_code = intval($_POST['province_code']);
        if ($province_code == 0) {
            echo json_encode(array('value' => '<option value="0">请选择</option>'));
        } else {
            $C = M('city');
            $city_list = $C->where("pro_code = $province_code")->select();
            $str = '';
            foreach ($city_list as $list) {
                if ($city == $list['city_name']) {
                    $str .= '<option value="' . $list['city_code'] . '" selected="selected">' . $list['city_name'] . '</option>';
                } else {
                    $str .= '<option value="' . $list['city_code'] . '">' . $list['city_name'] . '</option>';
                }
            }
            echo json_encode(array('value' => $str));
        }
    }

    /**
     * 检查修改的昵称是否可用
     *
     */
    function checkNickname() {
        $nick = session('user_nickname');
        $user_nickname = addslashes($_POST['user_nickname']);
        $user_province = addslashes($_POST['province']);
        $user_city = addslashes($_POST['city']);
        $User = M('user_base_info');
        $count = $User->where("user_nickname != '$nick' and user_nickname = '$user_nickname'")->count();
        if ($count) {
            echo json_encode(array('status' => 1, 'text' => '昵称已存在，请更换！'));
        } else {
            $data['user_nickname'] = $user_nickname;
            $data['user_province'] = $user_province;
            $data['user_city'] = $user_city;
            $user_code = session(C('USER_AUTH_KEY'));
            $User->where("user_code = $user_code")->save($data);
            session('user_nickname', $user_nickname);
            session('user_province', $user_province);
            session('user_city', $user_city);
            echo json_encode(array('status' => 2, 'text' => '修改成功！'));
        }
    }

    /**
     * 修改密码
     *
     */
    function passwd() {
        $user_id = session(C('USER_AUTH_KEY')); //用户id
        $User = M('user_base_info');
        $UserInfo = $User->where("user_code = $user_id")->find();
        //判断修改密码页面是显示绑定账号html还是显示验证邮箱html还是显示修改密码html
        if ($UserInfo['user_email']) {
            $display_type = 1;
        } else {
            $Account = M('bind_account');
            $user_code = session(C('USER_AUTH_KEY'));
            $bind_info = $Account->where("user_code = $user_code")->order("id desc")->find();
            if ($bind_info['user_email']) {
                $this->assign('bind_email', $bind_info['user_email']);
                $display_type = 2;
            } else {
                $display_type = 3;
            }
        }
        $this->assign('title', '修改密码 - ' . C('TITLE'));
        $this->assign('display_type', $display_type);
        $this->display();
    }

    /**
     * 校验修改的密码
     */
    function checkPasswd() {
        $user_email = session('user_email');
        $old_password = md5($_POST['old_password']); //旧密码
        $new_password = md5($_POST['new_password']); //新密码
        $User = M('user_base_info');
        $count = $User->where("user_email = '$user_email' and user_passwd = '$old_password'")->count();
        if ($count) {
            $data['user_passwd'] = $new_password;
            $user_code = session(C('USER_AUTH_KEY'));
            $User->where("user_code = $user_code")->save($data);
            //注销session和cookie
            session(null); //清空当前session
            session('[destroy]'); // 销毁session
            cookie(null);
            echo json_encode(array('status' => 2, 'text' => '修改成功！'));
        } else {
            echo json_encode(array('status' => 1, 'text' => '原始密码输入错误！'));
        }
    }

    /**
     * 更换头像
     *
     */
    function photo() {
        $user_id = session(C('USER_AUTH_KEY')); //用户id
        $User = M('user_base_info');
        $UserInfo = $User->where("user_code = $user_id")->find();
        if (empty($UserInfo['user_logo_add'])) {
            if (empty($UserInfo['api_logo_add'])) {
                $user_logo_add = __PUBLIC__ . "/Uploads/Photo/default_160.png";
            } else {
                //如果是qq用户
                if ($UserInfo['user_reg_type'] == 3) {
                    $user_logo_add = str_replace('/40', '/100', $UserInfo['api_logo_add']);
                } else {
                    //新浪用户
                    $user_logo_add = str_replace('/50/', '/180/', $UserInfo['api_logo_add']);
                }
            }
        } else {
            $user_logo_add = __PUBLIC__ . "/Uploads/Photo/" . str_replace('_64', '_160', $UserInfo['user_logo_add']);
        }
        $this->assign('title', '更换头像 - ' . C('TITLE'));
        $this->assign('user_logo_add', $user_logo_add);
        $this->display();
    }

    /**
     * 预览保存上传图片
     */
    function uploadPic() {
        import("@.ORG.UploadFile");
        $upload = new UploadFile();
        //设置上传文件大小
        $upload->maxSize = 2048000;
        //设置上传文件类型
        $upload->allowExts = explode(',', 'jpg,gif,png,jpeg');
        //设置附件上传目录
        $upload->savePath = $_SERVER['DOCUMENT_ROOT'] . __ROOT__ . '/Public/Uploads/Photo/';
        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb = true;
        // 设置引用图片类库包路径
        $upload->imageClassPath = '@.ORG.Image';
        //设置需要生成缩略图的文件后缀
        $upload->thumbPrefix = 'm_'; //产生1张缩略图
        //设置缩略图最大宽度
        $upload->thumbMaxWidth = '300';
        //设置缩略图最大高度
        $upload->thumbMaxHeight = '300';
        //设置上传文件规则
        $upload->saveRule = uniqid;
        //删除原图
        $upload->thumbRemoveOrigin = true;
        if ($upload->upload()) {
            $uploadList = $upload->getUploadFileInfo();
        }
        echo 'm_' . $uploadList[0]['savename'];
    }

    /**
     * 保存裁剪的头像
     */
    function uploadClipPic() {
        $x1 = intval($_POST['x1']);
        $y1 = intval($_POST['y1']);
        $w = intval($_POST['w']);
        $h = intval($_POST['h']);
        $source_photo = $_POST['source_photo'];
        if (empty($w)) $w = 160;
        if (empty($h)) $h = 160;
        $savePath = $_SERVER['DOCUMENT_ROOT'] . __ROOT__ . '/Public/Uploads/photo/';
        if (!file_exists($savePath . $source_photo)) {
            echo json_encode(array('status' => 1, 'text' => '原始图片不存在！'));
        } else {
            $user_code = $_SESSION[C('USER_AUTH_KEY')];
            import("@.ORG.ImageClip");
            $obj = new ImageClip($savePath . $source_photo, $savePath, 160, 160, $w, $h, $x1, $y1, $user_code . '_160.');
            $pic_creat = $obj->getCreateImg();
            $new_pic = $obj->createEmptyImage(); //创建空图像
            $obj->copyImage($new_pic, $pic_creat); //复制图像
            if ($obj->outImage($new_pic)) {
                //再保存小头像（64*64）
                unset($obj, $pic_creat, $new_pic);
                $obj = new ImageClip($savePath . $source_photo, $savePath, 64, 64, $w, $h, $x1, $y1, $user_code . '_64.');
                $pic_creat = $obj->getCreateImg();
                $new_pic = $obj->createEmptyImage(); //创建空图像
                $obj->copyImage($new_pic, $pic_creat); //复制图像
                $obj->outImage($new_pic);
                $ext = $obj->getExtend(); //后缀
                //删除原始图
                if (file_exists($savePath . $source_photo)) {
                    unlink($savePath . $source_photo);
                }
                //修改数据库并修改头像session值
                $data['user_logo_add'] = $user_code . '_64.' . $ext;
                $User = M('user_base_info');
                $User->where("user_code = $user_code")->save($data);
                session('user_logo_add', $user_code . '_64.' . $ext);
                echo json_encode(array('status' => 2, 'text' => '头像保存成功！'));
            } else {
                echo json_encode(array('status' => 1, 'text' => '头像保存失败！'));
            }
        }
    }

    /**
     * 第三方登录用户绑定账号
     */
    function bindAccount() {
        $user_email = $_POST['user_email'];
        $user_passwd = md5($_POST['user_passwd']);
        $auth = $_POST['auth'];
        //判断验证码是否正确
        $auth_array = C('AUTH_ARRAY');
        $key = $_SESSION['verify'];
        if ($auth != $auth_array[$key]) {
            echo 1; //验证码错误
        } else {
            //检测用户邮箱是否唯一
            $isExist = R('Public/checkuseremail', array($user_email, 2));
            if ($isExist == 1) {
                echo 2; //邮箱已存在
            } elseif ($isExist == 2) {
                //邮箱可以使用，下发邮件
                require_once(LIB_PATH . 'ORG/String.class.php');
                $email_key = base64_encode(String::rand_string(10));
                $link = C('WEB_URL') . '/index.php/Center/activation/user_email/' . $user_email . '/email_key/' . $email_key;
                $email_content = session('user_nickname') . '，你好<br>请点此<a href="' . $link . '">' . $link . '</a>绑定账号。如点击不了，请复制以上链接粘贴在浏览器中打开。<br><br><br>24淘祝您购物愉快！<br>' . date("Y-m-d");
                $send_email_status = $this->sendEmail(4, array($user_email), '24淘（www.24tao.com）提醒您绑定账号', $email_content, $email_key, 0);
                //插入数据至24_bind_acount
                $Account = M('bind_account');
                $data['user_code'] = session(C('USER_AUTH_KEY'));
                $data['user_email'] = $user_email;
                $data['user_passwd'] = $user_passwd;
                $data['email_key'] = $email_key;
                $data['create_datetime'] = date("Y-m-d H:i:s");
                if ($Account->add($data)) {
                    echo 3;
                } else {
                    echo 4;
                }
            }
        }
    }

    /**
     * 第三方登录绑定账号-验证邮箱
     */
    function activation() {
        $user_code = session(C('USER_AUTH_KEY'));
        $user_email = addslashes($_GET['user_email']);
        $email_key = addslashes($_GET['email_key']);
        $User = M('user_base_info');
        //判断是否已经激活了，防止用户恶意点击激活链接
        $count = $User->where("user_email = '$user_email'")->count();
        if ($count) {
            //邮箱已被使用
            $link_status = 1;
        } else {
            //未激活，判断激活链接是否有效
            $Account = M('bind_account');
            $rows = $Account->where("user_code = $user_code and user_email = '$user_email' and email_key = '$email_key'")->order('create_datetime desc')->find();
            if ($rows) {
                //更新用户数据
                $data['user_email'] = $user_email;
                $data['user_passwd'] = $rows['user_passwd'];
                $data['user_status'] = 2;
                $User->where("user_code = $user_code")->save($data);
                $link_status = 2;
                session('user_email', $user_email);
            } else {
                //此激活链接已失效
                $link_status = 3;
            }
        }
        $this->assign('title', '绑定账号验证邮箱 - ' . C('TITLE'));
        $this->assign('user_email', $user_email);
        $this->assign('link_status', $link_status);
        $this->display();
    }

    /**
     * 个人中心-好友
     */
    public function friend() {
        //我的关注还是我的粉丝
        $type = $_GET['type'];
        if(empty($type)){
            $type = 1;
        }
        if($type == 1){
            //我的关注
            $type_name = '我的关注';
        }else{
            //我的粉丝
            $type_name = '我的粉丝';
        }
        $this->assign('title', $type_name . ' - ' . C('TITLE'));
        $this->assign('type', $type);
        $this->display();
    }

    /**
     * 个人中心-消息
     */
    public function message() {
        //好友消息还是系统消息
        $type = $_GET['type'];
        if(empty($type)){
            $type = 1;
        }
        if($type == 1){
            //好友消息
            $type_name = '好友消息';
        }else{
            //系统消息
            $type_name = '系统消息';
        }
        $this->assign('title', $type_name . ' - ' . C('TITLE'));
        $this->assign('type', $type);
        $this->display();
    }

    /**
     * 个人中心-推荐
     */
    public function recommon() {
        //待审核、已拒绝、成功
        $type = $_GET['type'];
        if(empty($type)){
            $type = 1;
        }
        if($type == 1){
            //待审核
            $type_name = '我的推荐';
        }else if($type == 2){
            //已拒绝
            $type_name = '我的推荐';
        }else{
            //成功
            $type_name = '我的推荐';
        }
        $this->assign('title', $type_name . ' - ' . C('TITLE'));
        $this->assign('type', $type);
        $this->display();
    }

    /**
     * 个人中心-偶像
     */
    public function star() {
        $this->assign('title',  '我的偶像 - ' . C('TITLE'));
        $this->display();
    }

    /**
     * 个人中心-衣柜
     */
    public function wardrobe() {
        $this->assign('title',  '我的衣柜 - ' . C('TITLE'));
        $this->display();
    }

    /**
     * 个人中心-喜欢
     */
    public function enjoy() {
        $this->assign('title',  '我喜欢的宝贝 - ' . C('TITLE'));
        $this->display();
    }

}

?>